package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dongdongshop.constant.OssConstant;
import com.dongdongshop.pojo.SpecVo;
import com.dongdongshop.data.HttpResponseEnum;
import com.dongdongshop.data.Result;
import com.dongdongshop.pojo.goods.TbGoods;
import com.dongdongshop.pojo.goods.TbGoodsDesc;
import com.dongdongshop.pojo.item.TbItem;
import com.dongdongshop.pojo.item.TbItemCat;
import com.dongdongshop.pojo.seller.TbSeller;
import com.dongdongshop.pojo.specification.TbSpecificationOption;
import com.dongdongshop.pojo.typeTemplate.TbTypeTemplate;
import com.dongdongshop.service.GoodsServiceI;
import com.dongdongshop.service.ItemCatServiceI;
import com.dongdongshop.service.SpecificationOptionServiceI;
import com.dongdongshop.service.TemplateServiceI;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;


//@CrossOrigin//支持跨域的注解
@Controller
@RequestMapping("goods")
public class GoodsController {

    private final Logger logger= LoggerFactory.getLogger(GoodsController.class);

    @Reference
    private ItemCatServiceI itemCatServiceI;
    @Reference
    private TemplateServiceI templateServiceI;
    @Reference
    private GoodsServiceI goodsServiceI;
    @Reference
    private SpecificationOptionServiceI specificationOptionServiceI;

    @RequestMapping("showGoods")
    public String showGoods(){
        return "admin/goods_edit";
    }

    //三级联动
    @RequestMapping("category/{parentId}")
    @ResponseBody
    public Result<List<TbItemCat>> getItemParentId(@PathVariable("parentId")Long parentId){
        try {
            List<TbItemCat> catList=itemCatServiceI.getItemParentId(parentId);
            return Result.jsonResponse(HttpResponseEnum.OK).setData(catList);
        }catch (Exception e){
            logger.error("系统错误",e);
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }
    }

    //获取模板ID
    @RequestMapping("getTypeId/{id}")
    @ResponseBody
    public Result getTypeId(@PathVariable("id")Long id){
        try {
            Long typeId=itemCatServiceI.getTypeId(id);
            return Result.jsonResponse(HttpResponseEnum.OK).setData(typeId);
        }catch (Exception e){
            logger.error("系统错误",e);
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }
    }

    //获取品牌和扩展属性
    @RequestMapping("getItemTemplate/{typeId}")
    @ResponseBody
    public Result<TbTypeTemplate> getItemTemplate(@PathVariable("typeId")Long typeId){
        try {
            TbTypeTemplate typeTemplate=templateServiceI.getTempById(typeId);
            return Result.jsonResponse(HttpResponseEnum.OK).setData(typeTemplate);
        }catch (Exception e){
            logger.error("系统错误",e);
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }
    }

    //增加
    @RequestMapping("addGood")
    @ResponseBody
    public Result insertGoods(TbGoods goods, TbGoodsDesc goodsDesc,String itemListJson){
        System.out.println("item数据:"+itemListJson);
        try {
            //获取商家信息
            TbSeller seller =(TbSeller) SecurityUtils.getSubject().getPrincipal();
            goods.setSellerId(seller.getSellerId());
            String sellerName = seller.getName();
            goods.setAuditStatus("0");
            List<TbItem> list = JSON.parseArray(itemListJson, TbItem.class);
            System.out.println("list"+list.size());
            int i=goodsServiceI.insertGoods(goods,goodsDesc,sellerName,list);
            if (i>0){
            return Result.jsonResponse(HttpResponseEnum.OK);
            }else {
                return Result.jsonResponse(HttpResponseEnum.FAIL);
            }

        }catch (Exception e){
            logger.error("系统错误",e);
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }
    }



    //查询规格
    @RequestMapping("getSpecAndOption")
    @ResponseBody
    public Result getSpecAndOption(@RequestParam("typeId")Long typeId) {
        //根据id查询模板
        TbTypeTemplate tbTypeTemplate = templateServiceI.updateById(typeId);
        String specIds = tbTypeTemplate.getSpecIds();
        System.out.println("idwe："+specIds);
        //解析模板中的规格信息
        List<SpecVo> specDTOList = JSONObject.parseArray(specIds, SpecVo.class);
        //循环调用根据规格查询出规格选项并组装数据
        for (SpecVo spec : specDTOList) {

            List<TbSpecificationOption>  options =  specificationOptionServiceI.listOptionsBySpecId(spec.getId());
            spec.setOptions(options);
            System.out.println("数据内容"+spec);
        }
        return Result.jsonResponse(HttpResponseEnum.OK).setData(specDTOList);
    }


    @RequestMapping("upLoadFile")
    @ResponseBody
    public Result upLoadFile(@RequestParam(value = "myFile") MultipartFile myFile) {
        try{
            // Endpoint以杭州为例，其它Region请按实际情况填写。
            String endpoint = OssConstant.ENDPOINT;
// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
            String accessKeyId = OssConstant.ACCESSKEYID;
            String accessKeySecret = OssConstant.ACCESSKEYSECRET;
            String bucketName = OssConstant.BUCKETNAME;
// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            String objectName = myFile.getOriginalFilename();//上传文件的路径

// 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
            //String content = "Hello OSS";
            String url = null;//前台路径
            try {
                ossClient.putObject(bucketName, objectName, myFile.getInputStream());
                //拼接图片访问路径
                url = "http://" + bucketName + OssConstant.POINT+ objectName;

            } catch (IOException e) {
                e.printStackTrace();
                return Result.jsonResponse(HttpResponseEnum.FAIL);
            }

// 关闭OSSClient。
            ossClient.shutdown();
            return Result.jsonResponse(HttpResponseEnum.OK).setData(url);
        }catch (Exception e){
            logger.info("操作异常",e);
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }
    }

 /*   @RequestMapping("findOptionsById/{id}")
    @ResponseBody
    public Result findOptionsById(@PathVariable("id")Long id){
        try {
            List<TbSpecificationOption> optionList= specificationOptionServiceI.findOptionsById(id);
            return Result.jsonResponse(HttpResponseEnum.OK).setData(optionList);
        }catch (Exception e){
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }

    }*/

}
